import { PlusOutlined, UploadOutlined } from "@ant-design/icons"
import { Form, Input, InputNumber, Modal, Upload, Image, type UploadFile, Select, Button, message } from "antd"
import { forwardRef, useImperativeHandle, useState } from "react"
import { getBase64, type FileType } from "../../../../utils/loadFile"
import { store, uploadBook } from "../../../../api/welcome/book"

const { useForm } = Form

type FieldType = {
  title: string
  author?: string
  description?: string
  coverFile?: string
  publisher?: string
  publishYear?: number
  category?: string[]
  tags?: string[]
  summary?: string
  bookFile: string
}

export interface BookFormRef {
  openModal: () => void
}

const BookForm = forwardRef<BookFormRef, {
  update: () => void
}>(({ update }, ref) => {
  const [open, setOpen] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(false)
  const [form] = useForm()
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  useImperativeHandle(ref, () => ({
    openModal: openModal
  }));

  const openModal = () => {
    if (!loading) {
      setOpen(old => !old)
    }
  }

  const onOk = async () => {
    form.validateFields().then(async (value: any) => {
      const formData = new FormData();
      Object.keys(value).forEach((key: string) => {
        if (value[key]) {
          if (key == 'tags' || key == 'category') {
            formData.append(key, value[key].join(','))
          } else if (key == 'coverFile' || key == 'bookFile') {
            if (value[key].length > 0) {
              formData.append(key, value[key][0].originFileObj)
            }
          } else {
            formData.append(key, value[key])
          }
        }
      })
      setLoading(true)

      const res = await uploadBook(formData)
      if (res.code == 200) {
        message.success('上传成功，开始构建智能索引可能需要10-60分钟，请耐心等待！')
        const data = {
          ...res.data
        }

        const res2 = await store(data)
        if (res2.code == 200) {
          message.success("索引构建完成")
        }
        update()
        openModal()
      }
      setLoading(false)

    })
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  return <>
    <Modal
      title="添加书籍"
      open={open}
      onOk={onOk}
      loading={loading}
      onCancel={openModal}
      afterClose={() => form.resetFields()}
      maskClosable={false}
      classNames={{
        body: 'max-h-[480px] overflow-auto'
      }}
    >
      <Form
        name="bookForm"
        form={form}
        layout="vertical"
      >
        <Form.Item<FieldType>
          label="书名"
          name="title"
          rules={[{ required: true, message: '请输入书名' }]}
        >
          <Input placeholder="请输入书名" allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label="作者"
          name="author"
        >
          <Input placeholder="请输入作者" allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label="介绍"
          name="description"
        >
          <Input placeholder="请输入介绍" allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label="封面"
          name="coverFile"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload
            listType="picture-card"
            onPreview={handlePreview}
            beforeUpload={() => false}
            accept=".png,.jpg,.gif,.jpeg,.webp,.svg"
            maxCount={1}
          >
            <button style={{ border: 0, background: 'none' }} type="button">
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传文件</div>
            </button>
          </Upload>
        </Form.Item>
        <Form.Item<FieldType>
          label="出版社"
          name="publisher"
        >
          <Input placeholder="请输入出版社" allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label="出版年份"
          name="publishYear"
        >
          <InputNumber placeholder="请输入出版年份" className="!w-full" min={0} />
        </Form.Item>
        <Form.Item<FieldType>
          label="分类"
          name="category"
        >
          <Select
            mode="tags"
            placeholder="请输入分类"
            allowClear
          />
        </Form.Item>
        <Form.Item<FieldType>
          label="标签"
          name="tags"
        >
          <Select
            mode="tags"
            placeholder="请输入标签"
            allowClear
          />
        </Form.Item>
        <Form.Item<FieldType>
          label="摘要"
          name="summary"
        >
          <Input placeholder="请输入摘要" allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label="书籍"
          name="bookFile"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[{ required: true, message: '请上传书籍' }]}
        >
          <Upload
            beforeUpload={() => false}
            accept=".pdf,.txt"
            maxCount={1}
          >
            <Button icon={<UploadOutlined />}>上传文件</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
    {previewImage && (
      <Image
        wrapperStyle={{ display: 'none' }}
        preview={{
          visible: previewOpen,
          onVisibleChange: (visible) => setPreviewOpen(visible),
          afterOpenChange: (visible) => !visible && setPreviewImage(''),
        }}
        src={previewImage}
      />
    )}
  </>
})

export default BookForm